/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
// general
var path,playlistdiv,inforDiv;
var audio,canvas,current,id,type,currentsongid;
var video;
// for result
var rs,playlist=[],lyricslist=[];
var artists,songs;
var isMV;
var isViewed;
var isLiked;
//--------------------------------- Controller --------------------------------- //
function Initilize(pid,ptype,context){
    // get param.
    isMV = "";
    isViewed = false;
    id = pid;
    type = ptype;
    path = context;
    playlistdiv = document.getElementById('list_control');
    inforDiv = document.getElementById('information');
    playerDiv = document.getElementById("player");
    // call ajax get result.
    var xmlhttp = getXMLHttpRequest();

    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status==200){
            rs = xmlhttp.responseXML;
            testxml = new XMLSerializer().serializeToString(rs);
            Processing();
        }
    }

    xmlhttp.open("POST","AjaxMusicPlayerServlet?id="+id+"&type="+type,true);
    xmlhttp.send();

}
//--------------------------------- Controller --------------------------------- //
function Processing(){
    canvas = document.getElementById("canvas");
    // get playlist
    if(typeof(rs)!='undefined'){
        DisplayControl();
        // set source default
        Autoplay();
    }
}
//--------------------------------- Audio Controller --------------------------------- //
function tooglePlayPause(){
    var playpause = document.getElementById("play_control");
    if(audio.paused || audio.ended){
        playpause.style["background-image"] = "url(img/mp-pause.png)";
        stopAnotherAudios();
        audio.play();
    }else{
        playpause.style["background-image"] = "url(img/mp-play.png)";
        audio.pause();
    }
}
//--------------------------------- Audio Controller --------------------------------- //
function setVolume(){
    var volume = document.getElementById("volume");
    audio.volume = volume.value;
}
//--------------------------------- Audio Controller --------------------------------- //
function toogleMute(){
    audio.muted = !audio.muted;
}
//--------------------------------- Audio Controller --------------------------------- //
function changeSource(e,id) {
    e.preventDefault();
    var src = path+"/"+playlist[id].source;
    audio.src = src;
    audio.load();
    current = id;
    currentsongid = playlist[id].songid;

    PrepareLyrics(lyricslist[id]);

    return false;
}
//--------------------------------- Audio Controller --------------------------------- //
function progressControl(){
    var elapsedTime = Math.round(audio.currentTime);
    if(elapsedTime > Math.round(audio.duration/2)){
        if(!isViewed){
            // neu' chua view thi` add them 1.
            isViewed = true;
        }
    }
    // update the progress bar
    if(canvas.getContext){
        var ctx = canvas.getContext("2d");
        // clear canvas before painting
        ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
        ctx.fillStyle="rgb(255,0,0)";
        var fwidth = (elapsedTime/audio.duration) * (canvas.clientWidth);
        if(fwidth > 0){
            ctx.fillRect(0,0,fwidth,canvas.clientHeight);
        }
    }
}
//--------------------------------- Audio Controller --------------------------------- //
function Autoplay(){
    if(typeof(video)!='undefined'){
        if(playlist.length>0){
            current=0;
            currentsongid = playlist[0].songid;
            video.src=path + playlist[0].source;
            video.load();
            video.play();
        }
    }else{
        if(playlist.length>0){
            current=0;
            currentsongid = playlist[0].songid;
            audio.src=path + playlist[0].source;
            audio.load();
            audio.play();
        }
    }

    PrepareLyrics(lyricslist[0]);
}
//--------------------------------- Display --------------------------------- //
function DisplayControl(){
    songs = rs.getElementsByTagName("Song");
    artists = [];

    // Display information
    LoadInformation();
    // Display playlist
    LoadPlaylist();
}
//--------------------------------- Display --------------------------------- //
function LoadPlaylist(){
    var out="";
    var playlistdiv = document.getElementById('list_song');
    // Display List
    out+="<ul class='playlist'>";
    if(type==2){
        out+=LoadPlaylistForAlbum();
    }else if(type==3){
        out+=LoadPlaylistForPlaylist();
    }
    out+="</ul>"
    playlistdiv.innerHTML = out;
}
//--------------------------------- Display --------------------------------- //
function LoadPlaylistForAlbum(){
    var out ="";
    var va = rs.getElementsByTagName("VariousArtist")[0].firstChild.nodeValue;
    if(!va){
        for(var i=0;i<songs.length;i++){
            // get source
            var songid = songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
            var src = songs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
            var artistName = rs.getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
            var albumName = rs.getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
            var source = "/db/"+artistName+"/Album/"+albumName+"/"+src+".mp3";
            var lyrics = songs[i].getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
            // add source to list
            lyricslist.push(lyrics);
            playlist.push({
                songid:songid,
                source:source
            });
            // display
            out+="<li class='playlist_item'>";
            out+="<a class='song_item' href='#' onclick=changeSource("+(playlist.length-1)+")>"
            out+=songs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
            out+="</a>";
            out+="</li>";
        }
    }else{
        out+=LoadPlaylistForPlaylist();
    }

    return out;
}
//--------------------------------- Display --------------------------------- //
function LoadPlaylistForPlaylist(){
    var out="";
    for(var i=0;i<songs.length;i++){
        // get source
        var songid = songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
        var src = songs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
        var artistName = rs.getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
        var albumName = rs.getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
        var source = "/db/"+artistName.removeDotCharacter()+"/Album/"+albumName.removeDotCharacter()+"/"+src+".mp3";
        var lyrics = songs[i].getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
        // add source to list
        lyricslist.push(lyrics);
        playlist.push({
            songid:songid,
            source:source
        });
        // display
        out+="<li class='playlist_item'>";
        out+="<a class='song_item' href='?id="+songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue +"' onclick='changeSource(event,"+(playlist.length-1)+")'>"
        out+=songs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
        out+="</a>";

        var artists = songs[i].getElementsByTagName("Artist");
        if(artists.length!=0){
            out+=" - ";
            for(var j=0;j<artists.length;j++){
                out+="<a href='artist.jsp?artistID="+artists[j].getElementsByTagName("ArtistID")[0].firstChild.nodeValue+"'>"
                out+=artists[j].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
                out+="</a>";
                if(j<artists.length-1){
                    out+=", ";
                }
            } // end for
        }

        out+="</li>";
    }

    return out;
}
//--------------------------------- Display --------------------------------- //
function LoadInformationForAlbum(){
    var out="";

    var coversrc = rs.getElementsByTagName("AlbumCoverSRC")[0].firstChild.nodeValue;
    var title = rs.getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
    if((rs.getElementsByTagName("AlbumDescription")[0].firstChild)!=null){
        var description = rs.getElementsByTagName("AlbumDescription")[0].firstChild.nodeValue;
    }
    var views = rs.getElementsByTagName("AlbumViews")[0].firstChild.nodeValue;
    var artistName = rs.getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
    //artistName = removeDotCharacter(artistName);
    
    // for send link
    
    // for send link
    var artistID = rs.getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
    var src = path + "/db/" + artistName.removeDotCharacter() + "/Album/"
    +title.removeDotCharacter()+"/"+coversrc;
    if(!isFileExists(src)){
        src = path+"/img/DefaultAlbumCover.jpg";
    }
    // output
    // image
    out+="<img src='"+src+"'></img>";
    // title
    out+="<br/>";
    out+="<p>"+title+"</p>";
    // artist name
    out+="<br/>";
    out+="<p>Nghệ sỹ: <a href='artist.jsp?id="+artistID+"'>"+artistName+"</a></p>";
    // album description
    if(description!=null){
        out+="<br/>";
        out+="<p>Mô tả: "+description+"</p>";
    }
    // views
    out+="<br/>";
    out+="<p>"+views+" lượt nghe</p>";
    //
    // display
    return out;
}
function LoadInformationForPlaylist(){
    var out="";

    var coversrc = rs.getElementsByTagName("PlaylistCover")[0].firstChild.nodeValue;
    if(coversrc==null){
        coversrc = "DefaultAlbumCover.jpg";
    }
    var name = rs.getElementsByTagName("PlaylistName")[0].firstChild.nodeValue;
    if((rs.getElementsByTagName("PlaylistDescription")[0].firstChild)!=null){
        var description = rs.getElementsByTagName("PlaylistDescription")[0].firstChild.nodeValue;
    }
    var likes = rs.getElementsByTagName("PlaylistLikeNumber")[0].firstChild.nodeValue;
    var views = rs.getElementsByTagName("ListenNumber")[0].firstChild.nodeValue;
    var username = rs.getElementsByTagName("Username")[0].firstChild.nodeValue;
    var lyrics = rs.getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
    // for send link
    lyricslist.push(lyrics);
    var playlistID = rs.getElementsByTagName("PlaylistID")[0].firstChild.nodeValue;
    var src = path + "/db/Playlist/" + name.removeDotCharacter() +
    "/"+coversrc;
    // output
    // image
    out+="<img src='"+src+"'></img>";
    // title
    out+="<br/>";
    out+="<p>"+name+"</p>";
    // artist name
    out+="<br/>";
    out+="<p> Người tạo: "+username+"</p>";
    // album description
    if(description!=null){
        out+="<br/>";
        out+="<p> Mô tả: "+description+"</p>";
    }
    // views
    out+="<br/>";
    out+="<p>"+views+" lượt nghe</p>";
    // views
    out+="<br/>";
    out+="<p>"+likes+" người thích</p>";
    //
    // display
    return out;
}
function LoadInformationForSong(){
    var out="";

    var isMV = rs.getElementsByTagName("isMV")[0].firstChild.nodeValue;
    // Info
    var title = rs.getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
    var views = rs.getElementsByTagName("SongViews")[0].firstChild.nodeValue;
    var likers = rs.getElementsByTagName("Username");
    var likes = likers.length;

    var coversrc = rs.getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
    // src
    var artistName = rs.getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
    var lyrics = rs.getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
    lyricslist.push(lyrics);
    // for send link
    var artistID = rs.getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
    if(isMV=="false"){
        var albumTitle = rs.getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
        var albumID = rs.getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
        var src = "/db/" + artistName.removeDotCharacter() + "/Album/"
        +albumTitle.removeDotCharacter()+"/"+coversrc+".mp3";
        playlist.push({
            songid:id,
            source:src
        });
    }else{
        var src = "/db/" + artistName.removeDotCharacter() + "/MV/"
        +coversrc + ".webm";
        playlist.push({
            songid:id,
            source:src
        });
    }

    // title
    out+="<p>"+title+"</p>";
    // artist name
    out+="<br/>";
    out+="Nghệ sỹ: <a href='artist.jsp?id="+artistID+"'>"+artistName+"</a>";
    // artist name
    out+="<br/>";
    if(isMV!="true"){
        out+="Album: <a href='musicplayer.jsp?id="+albumID+"&type=2'>"+albumTitle+"</a>";
    }
    // views
    out+="<br/>";
    out+="<p>"+views+"lượt nghe</p>";
    // likes
    out+="<br/>";
    out+="<p>"+likes+"người thích</p>";
    // display
    return out;
}
// -----------------------------------------DISPLAY ------------------------------------
function LoadInformation(){
    var out="";

    out+="<ul>";
    if(type==1){
        out+=LoadInformationForSong();
        PrepareAudioPlayer();
    }else if(type==2){
        out+=LoadInformationForAlbum();
        PrepareAudioPlayer();
    }else if(type==3){
        out+=LoadInformationForPlaylist();
        PrepareAudioPlayer();
    }else if(type==4){
        out+=LoadInformationForSong();
        PrepareMVPlayer();
    }
    out+="</ul>";

    inforDiv.innerHTML = out;
}

function PrepareMVPlayer(){
    video = document.createElement("video");
    document.getElementById("player").appendChild(video);
    video.setAttribute('controls', true);
    video.setAttribute('class', "video_player");

    // progress bar
    video.addEventListener("timeupdate", progressControl, false);
    // when play
    video.addEventListener("play", function(){
        var playpause = document.getElementById("play_control");
        playpause.style["background-image"] = "url(img/mp-pause.png)";
    }, false)
    // when pause
    video.addEventListener('pause', function(){
        var playpause = document.getElementById("play_control");
        playpause.style["background-image"] = "url(img/mp-play.png)";
    }, false)

    // when canvas click, change currentTime
    canvas.addEventListener("click", function(e){
        if(!e){
            e = window.event;
        }
        if(typeof(video)!='undefined'){
            try{
                audio.currentTime = audio.duration*(e.offsetX/canvas.clientWidth);
            }catch(err){
                if(window.console && console.error("Error: "+err));
            }
        }else{
            try{
                video.currentTime = video.duration*(e.offsetX/canvas.clientWidth);
            }catch(err){
                if(window.console && console.error("Error: "+err));
            }
        }
    }, true);
}

function PrepareAudioPlayer(){
    audio = document.createElement("audio");
    document.getElementById("player").appendChild(audio);
    audio.setAttribute("autoplay", "true");
    isView = false;

    // progress bar
    audio.addEventListener("timeupdate", progressControl, false);
    // when play
    audio.addEventListener("play", function(){
        var playpause = document.getElementById("play_control");
        stopAnotherAudios();
        playpause.style["background-image"] = "url(img/mp-pause.png)";
    }, false);
    // when pause
    audio.addEventListener('pause', function(){
        var playpause = document.getElementById("play_control");
        playpause.style["background-image"] = "url(img/mp-play.png)";
    }, false);

    audio.addEventListener('ended', endedListener, false);

    // when canvas click, change currentTime
    canvas.addEventListener("click", function(e){
        if(!e){
            e = window.event;
        }
        try{
            audio.currentTime = audio.duration*(e.offsetX/canvas.clientWidth);
        }catch(err){
            if(window.console && console.error("Error: "+err));
        }
    }, true);
}

function PrepareLyrics(item){
    RemoveLyrics();
    var lyricDiv = document.createElement("div");
    lyricDiv.setAttribute("id", "lyricsarea");

    // seperate
    var items = seperateSentences(item);
    var out = "";
    for(var i=0;i<items.length;i++){
        out += "<p>" + items[i] + "</p>";
    }
    lyricDiv.innerHTML = out;

    var parentDiv = document.getElementById("lyrics");
    parentDiv.appendChild(lyricDiv);
}

function RemoveLyrics(){
    var parentDiv = document.getElementById("lyrics");

    var list = parentDiv.getElementsByTagName("div");
    for(var i=0;i<list.length;i++){
        parentDiv.removeChild(list[i]);
    }
}

function ControlAction(){
    var action = "like";
    var xmlHttp = getXMLHttpRequest();
    // prepare url
    if(isViewed){
        if(isLiked){
            action = "both";
        }else{
            action = "view";
        }
    }

    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState==4 && xmlHttp.status == 200){
            var d = new Date();
            var year = d.getFullYear();
            var week = getWeekNo();
            xml = new XMLSerializer().serializeToString(loadXMLDoc(context+"/xml/history/"+year+"/week"+week+".xml"));
            localStorage.setItem("historyxml",xml);
        }
    }

    xmlHttp.open("POST","AjaxActionServlet?action="+action+
        "&songid="+currentsongid+"&id="+id+"&type="+type,true);
    xmlHttp.send();
}

function endedListener(){
    var src;
    // submit action.
    if(isLiked==true || isViewed==true){
        ControlAction();
    }
    // move to next song.
    if(current==playlist.length-1){
        src = path + "/" + playlist[0].source;
        audio.src = src;
        currentsongid = playlist[0].songid;
        current = 0;
        PrepareLyrics(lyricslist[0]);
    }else{
        current = current + 1;
        src = path + "/" + playlist[current].source;
        audio.src = src;
        currentsongid = playlist[current].songid;
        PrepareLyrics(lyricslist[current]);
    }
    audio.load();
}

function stopAnotherAudios(){
    var another = document.getElementById("masterPlayer");
    if(!another.paused){
        another.pause();
    }
}
